import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/city_pick.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/poi_search.dart';
import 'package:t3_track/t3_track.dart';
import 'package:uikit/uikit.dart';
import 'package:t3_foundation/t3_foundation.dart';
import '../../../configs/poi_search_base_config.dart';
import '../../../configs/poi_search_single_point_config.dart';
import '../../model/const.dart';
import '../../page/poi_search_channel.dart';
import '../../view_model/poi_search_bar_view_model.dart';
import '../../view_model/poi_search_cell_view_model.dart';
import 'input_item_widget.dart';

class T3SingleInputBoard extends StatefulWidget {
  final POISearchSinglePointConfig searchConfig;
  final POISearchBarViewModel viewModel;

  final ValueChanged<T3SearchCondition> onSearchConditionDidChanged;
  final ValueChanged<List<POISearchCellViewModel>> onFinishSelection;

  T3SingleInputBoard({
    super.key,
    required this.viewModel,
    required this.searchConfig,
    required this.onFinishSelection,
    required this.onSearchConditionDidChanged,
  });

  @override
  _T3SingleInputBoardState createState() => _T3SingleInputBoardState();
}

class _T3SingleInputBoardState extends State<T3SingleInputBoard> {
  late T3SearchCondition condition;
  late Worker worker;

  var autoOpenCity = false;
  FocusNode focusNode = FocusNode();
  @override
  void initState() {
    super.initState();

    condition = T3SearchCondition(
        adCode: widget.searchConfig.location?.adCode ?? '',
        cityName: widget.searchConfig.location?.cityName ?? '',
        coordinate:
            widget.searchConfig.location?.coordinate ?? const LatLng(0, 0),
        poiType: widget.searchConfig.pointType,
        supplier: widget.searchConfig.mapType);
    condition.keyword = widget.searchConfig.defaultText;

    //logPOISearchDebug('单选初始化条件：${condition.toString()}');
    widget.onSearchConditionDidChanged(condition);

    worker = ever(widget.viewModel.currentSelectedModel, (value) {
      //logPOISearchDebug('监听到单选结果：${value.jsonOutput(false).toString()}');
      widget.onFinishSelection([value]);
    });

    if (condition.adCode.isNullOrEmpty()) {
      var result = POISearchChannel.patchCondition(condition.coordinate);
      result.then((value) {
        if (value.item1.isNotNullAndEmpty()) {
          condition.adCode = value.item1;
          //logPOISearchDebug('单选经纬度补偿adCode成功');
        }
        if (value.item2.isNotNullAndEmpty() &&
            condition.cityName.isNullOrEmpty()) {
          condition.cityName = value.item2;
        }
      });
    }
    autoOpenCity = widget.searchConfig.autoOpenCitySelection &&
        widget.searchConfig.pointType == T3POIType.start;
    if (autoOpenCity) {
      autoOpenCity = false;
      Future.delayed(const Duration(milliseconds: 100), () {
        openCity(true);
      });
    }
  }

  @override
  void dispose() {
    //logPOISearchDebug('单选输入框销毁');
    worker.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      height: InputConst.kInputItemHeight,
      child: T3KeywordInputItemWidget(
        textGetter: () {
          return condition.keyword;
        },
        isFirstResponder: true,
        focusNode: focusNode,
        searchConfig: widget.searchConfig,
        placeholder: widget.searchConfig.placeholder ??
            widget.searchConfig.pointType.placeholder(),
        onTextChanged: (value) {
          final newCondition = T3SearchCondition(
              adCode: condition.adCode,
              cityName: condition.cityName,
              coordinate: condition.coordinate);
          newCondition.poiType = condition.poiType;
          newCondition.supplier = condition.supplier;
          newCondition.keyword = value;
          widget.onSearchConditionDidChanged(newCondition);
          condition.keyword = value;
        },
        dotColor: condition.poiType.dotColor(widget.searchConfig.style),
        dotImageName: null,
        cityName: condition.cityName ?? "",
        onCityTapped: () {
          openCity(false);
        },
      ),
    );
  }

  String showCityName(String named) {
    var name = named;
    if (name.endsWith('市')) {
      name = name.substring(0, name.length - 1);
    }
    return name;
  }

  openCity(bool isAuto) {
    if (!isAuto) {
      if (widget.searchConfig.pageScene == PageScene.mapSelectSearch) {
        switch (widget.searchConfig.pointType) {
          case T3POIType.start:
            T3Track.trackEventName('019902100000102');
            break;
          case T3POIType.via:
            T3Track.trackEventName('019903900000102');
            break;
          case T3POIType.end:
            T3Track.trackEventName('019903700000102');
            break;
        }
      } else {
        if (widget.searchConfig.isStartPoint) {
          T3Track.trackEventName('019900600000102');
        } else {
          T3Track.trackEventName('019900800000102');
        }
      }
    }
    var result = BoostNavigator.instance.push('cityPickerPage', arguments: {
      'hintText': widget.searchConfig.pointType.cityPlaceHolder(),
      'cityScope': widget.searchConfig.cityScope.value,
      'autoPop': true,
      'showBack': widget.searchConfig.showBackButton,
      'isFromFlutter': true,
    });
    result.then((value) {
      if (value != null) {
        var body = value as Map?;
        if (body != null) {
          var result = body['result'];
          if (result == 'data') {
            var cityData = body['data'];
            if (cityData != null) {
              var city = HostModel.fromJson(cityData);
              //logPOISearchDebug('单选：城市选择页切换城市${city.toJson().toString()}');

              var lat = city.latitude ?? condition.coordinate?.latitude;
              var lng = city.longitude ?? condition.coordinate?.longitude;
              if (lat != null && lng != null && lat != 0 && lng != 0) {
                final newCondition = T3SearchCondition(
                    adCode: city.adCode,
                    cityName: city.city,
                    coordinate: LatLng(lat, lng));
                newCondition.poiType = condition.poiType;
                newCondition.supplier = condition.supplier;
                newCondition.keyword = '';
                widget.onSearchConditionDidChanged(newCondition);
              }
              condition.updateCity(city);
              setState(() {});
            }
          }
        }
      }
      Future.delayed(const Duration(milliseconds: 100), () {
        FocusScope.of(context).requestFocus(focusNode);
      });
    });
  }
}
